package com.hdit.guimei.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyuncs.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @基本功能: 使用阿里云Oss对象存储
 * @ClassName: OssUtil
 * @Description: TODO
 * @Author: 李嘉明
 * @Date: 2021/1/19 16:13
 * @Version 1.0
 */
public class OssUtil {
    private static String ENDPOINT = "oss-cn-beijing.aliyuncs.com"; //外网访问节点
    private static String ACCESSKEYID = "LTAI4GEiCv7V3iwhjrg8SucD"; //公钥
    private static String ACCESSKEYSECRET = "YVI8mdBT40gDulihch307XrMEk1yso"; //公钥密码
    private static String BUKETNAMME = "lijiaming0502"; //oss仓库名字
    private static String SUFFR_URL = "http://lijiaming0502.oss-cn-beijing.aliyuncs.com/"; //上传成功后返回的url地址
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    public OSSClient getOSSClient() {
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
        if (ossClient.doesBucketExist(BUKETNAMME)) {
            System.out.println("bucket创建成功！");
        } else {
            //如果访问的仓库不存在，则创建新的仓库
            System.out.println("bucket不存在，创建bucket:" + BUKETNAMME);
            //创建一个oss仓库
            CreateBucketRequest bucketRequest = new CreateBucketRequest(null);
            bucketRequest.setBucketName(BUKETNAMME);
            bucketRequest.setCannedACL(CannedAccessControlList.PublicRead);//设置权限为公共读
            ossClient.createBucket(bucketRequest);
            ossClient.shutdown();
        }
        return ossClient;
    }

    /**
     * @Method: uploadDocument
     * @函数(方法)功能: 上传文件
     * @Author: 李嘉明
     * @params: [multipartFile, businessType] 文件+文件类型
     * @Return: java.lang.String
     * @Exception:
     * @Date: 2021/1/19 17:22
     */
    public String uploadDocument(MultipartFile multipartFile, String businessType) {
        //获取oss连接
        OSSClient ossClient = this.getOSSClient();
        //获取文件的后缀名
        String ext = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        //上传至oss的哪个文件夹，通过filename来指定生成规则// www.baidu.com/img/20210119/aaaa.jpg
        String fileName = getFileName(businessType, ext);

        String url = null;
        //通过ossClient来获取上传文件后返回的url
        try {
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("image/jpg");
            ossClient.putObject(BUKETNAMME, fileName, new ByteArrayInputStream(multipartFile.getBytes()));
            //成功以后返回的
            url = SUFFR_URL + fileName;
            System.out.println("------>>>>>>上传资料成功，oss地址url：" + url);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();//关闭连接
        }
        return url;
    }

    /**
     * @Method: getFileName
     * @函数(方法)功能: 上传文件到oss对象存储
     * @Author: 李嘉明
     * @params: [businessType, ext]
     * @Return: java.lang.String
     * @Exception:
     * @Date: 2021/1/19 17:49
     */
    private String getFileName(String businessType, String ext) {
        String date = sdf.format(new Date());
        if (StringUtils.isEmpty(businessType)) {  //判断类型是否无值
            businessType = "default";
        }
        //为了避免图片命名，使用uuid来命名图片
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //组合filename
        String filename = businessType + "/" + date + "/" + uuid + ext;
        return filename;
    }

//    public static void main(String[] args) throws  Exception{
//      File f = new File("C:\\Users\\李嘉明\\Desktop\\ideaBG\\bg.jpg");
//        FileInputStream in_file = new FileInputStream(f);
//        MultipartFile multipartFile = new MockMultipartFile("bg.jpg","bg.jpg","jpg",in_file);
//        String url = new OssUtil().uploadDocument(multipartFile,"jpg");
//        System.out.println(url);
//    }
}
